package net.hvacapp.cmvrfforandroid.ui;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import net.hvacapp.cmvrfforandroid.AppManager;
import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.manager.ProjectManager;
import net.hvacapp.cmvrfforandroid.model.GetUnreadMessageResp;
import net.hvacapp.cmvrfforandroid.ui.EventBus.NewMessageRefreshEvent;
import net.hvacapp.cmvrfforandroid.ui.fragment.MineFragment;
import net.hvacapp.cmvrfforandroid.ui.fragment.MineFragment_;
import net.hvacapp.cmvrfforandroid.ui.fragment.ProductFragment;
import net.hvacapp.cmvrfforandroid.ui.fragment.ProductFragment_;
import net.hvacapp.cmvrfforandroid.ui.fragment.ProjectFragment;
import net.hvacapp.cmvrfforandroid.ui.fragment.ProjectFragment_;
import net.hvacapp.cmvrfforandroid.ui.fragment.ResourceFragment;
import net.hvacapp.cmvrfforandroid.ui.fragment.ResourceFragment_;
import net.hvacapp.cmvrfforandroid.ui.project.ProjectStep1Activity;
import net.hvacapp.cmvrfforandroid.utils.AnnotationUtil;
import net.hvacapp.cmvrfforandroid.widget.IOSAlertView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import de.greenrobot.event.EventBus;

@EActivity(R.layout.activity_main_tab_bar)
public class MainTabBarActivity extends BaseActivity {

    @ViewById
    TextView tv_project;
    @ViewById
    TextView tv_product;
    @ViewById
    TextView tv_resource;
    @ViewById
    TextView tv_me;
    
    ProjectFragment mProjectFragment;
    ProductFragment mProductFragment;
    ResourceFragment mResourceFragment;
    MineFragment mMineFragment;


    /**
     * 页面加载完后执行
     */
    @AfterViews
    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        EventBus.getDefault().register(this);
        initTabPosition(0);
    }

    /**
     * 初始化
     */
    @Override
    public void initBoot() {
    }

    /**
     * 初始化数据
     */
    @Override
    public void initData(Intent intent) {
        loadUnreadSuggestionCount();
        loadUnreadNoticeCount();
    }

    /**
     * 联系人任务未处理
     *
     * @param event
     */
    public void onEvent(NewMessageRefreshEvent event) {
        loadUnreadSuggestionCount();
        loadUnreadNoticeCount();
    }

    private void loadUnreadSuggestionCount() {

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_UNREAD_SUGGESTIONS, AccountManager.getInstance().getToken(), new HttpCallbackHandle<GetUnreadMessageResp>() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onSuccess(GetUnreadMessageResp obj) {
                // 成功
                if (obj != null && obj.getGetUnReadSuggestionResult() > 0) {
                    tv_me.setCompoundDrawablesRelativeWithIntrinsicBounds(0, R.drawable.tab_resource_red, 0, 0);
                } else {
                    tv_me.setCompoundDrawablesRelativeWithIntrinsicBounds(0, R.drawable.tab_resource, 0, 0);
                }
            }

            @Override
            public void onFailure(String response) {

            }

        });
    }

    private void loadUnreadNoticeCount() {

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_UNREAD_NOTICES, AccountManager.getInstance().getToken(), new HttpCallbackHandle<GetUnreadMessageResp>() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onSuccess(GetUnreadMessageResp obj) {
                // 成功
                if (obj != null && obj.getGetUnReadPostResult() > 0) {
                    tv_resource.setCompoundDrawablesRelativeWithIntrinsicBounds(0, R.drawable.tab_mine_red, 0, 0);
                } else {
                    tv_resource.setCompoundDrawablesRelativeWithIntrinsicBounds(0, R.drawable.tab_mine, 0, 0);
                }
            }

            @Override
            public void onFailure(String response) {

            }

        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    /**
     * 页面名称
     */
    @Override
    public String getName() {
        return "";
    }

    @Click({R.id.tv_project,R.id.tv_product,R.id.tv_resource,R.id.tv_me})
    void onClick(View v){
        switch (v.getId()){
            case R.id.tv_project:
                initTabPosition(0);
                break;
            case R.id.tv_product:
                initTabPosition(1);
                break;
            case R.id.tv_resource:
                initTabPosition(2);
                break;
            case R.id.tv_me:
                initTabPosition(3);
                break;
        }
    }

    /**
     * 初始化底部菜单
     *
     * @param position
     */
    private void initTabPosition(int position) {
        clearAllTabs();
        // 开启一个Fragment事务
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        switch (position) {
            case 0:
                tv_project.setSelected(true);
                setupToolbar("项目");
//                setupToolbar(0, "项目", null);
//                int ids[] = {R.id.action_new};
//                int icons[] = {R.drawable.new_project};
//                setupToolbarMenuItem(ids, icons, new String[]{"新建项目"}, null);
                hidBackBtn();
                setButton1Info("新建项目", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ProjectManager.getInstance().setStatus(ProjectManager.PROJECT_STATUS_NEW);
                        ProjectManager.getInstance().setProjectData(null);
                        startActivity(AnnotationUtil.get(ProjectStep1Activity.class));
                    }
                });
                if (mProjectFragment == null) {
                    mProjectFragment = ProjectFragment_.builder().build();
                    transaction.add(R.id.fl_content, mProjectFragment);
                } else {
                    transaction.show(mProjectFragment);
                }
                break;
            case 1:
                tv_product.setSelected(true);
                setupToolbar("产品");
                hidBackBtn();
                setButton1Info(null, null);
//                setupToolbarMenuItem(null, null, null, null);
                if (mProductFragment == null) {
                    mProductFragment = ProductFragment_.builder().build();
                    transaction.add(R.id.fl_content, mProductFragment);
                } else {
                    transaction.show(mProductFragment);
                }
                break;
            case 2:
                tv_resource.setSelected(true);
                setupToolbar("资源");
                hidBackBtn();
                setButton1Info(null, null);
//                setupToolbarMenuItem(null, null, null, null);
                if (mResourceFragment == null) {
                    mResourceFragment = ResourceFragment_.builder().build();
                    transaction.add(R.id.fl_content, mResourceFragment);
                } else {
                    transaction.show(mResourceFragment);
                }
                break;
            case 3:
                tv_me.setSelected(true);
                setupToolbar("我");
                hidBackBtn();
                setButton1Info(null, null);
//                setupToolbarMenuItem(null, null, null, null);
                if (mMineFragment == null) {
                    mMineFragment = MineFragment_.builder().build();
                    transaction.add(R.id.fl_content, mMineFragment);
                } else {
                    transaction.show(mMineFragment);
                }
                break;
            default:
                break;
        }
        transaction.commit();
    }


    /**
     * @param transaction
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (mProjectFragment != null) {
            transaction.hide(mProjectFragment);
        }

        if (mProductFragment != null) {
            transaction.hide(mProductFragment);
        }

        if (mResourceFragment != null) {
            transaction.hide(mResourceFragment);
        }

        if (mMineFragment != null) {
            transaction.hide(mMineFragment);
        }
    }

    /**
     * 清楚所有tab选择状态
     */
    private void clearAllTabs() {
        tv_project.setSelected(false);
        tv_product.setSelected(false);
        tv_resource.setSelected(false);
        tv_me.setSelected(false);
    }

    /**
     * 点击返回按钮执行弹出框退出确认， 如果加了淘宝入口，就去掉这个函数的定义
     */
    @Override
    public void onBackPressed() {


        // 执行退出
        IOSAlertView.showAlertView(MainTabBarActivity.this, "提示", "确定退出应用?", "确定",
                new IOSAlertView.OnAlertViewClickListener() {

                    @Override
                    public void OnAlertViewClick(int position) {
                        if (position == 0) {

                            // 清除数据
                            AccountManager.getInstance().logout();

                            // 停止体检服务

                            AppManager.getAppManager().AppExit();
                        }
                    }
                }, "取消");
    }
    
}
